<template>
  <div class="answer-tree tdesign-starter-layout">
    <t-select-input
      :value="selectValue"
      placeholder="请选择"
      :tag-input-props="{ excessTagsDisplayType: 'scroll' }"
      :popup-props="{
        attach: '.answer-tree',
        overlayStyle: { weight: '100%', overflow: 'auto' },
      }"
      clearable
      multiple
      @tag-change="onTagChange"
      @clear="selectValue = []"
    >
      <template #panel>
        <t-checkbox-group
          :value="checkboxValue"
          :options="currentCheckboxOptions"
          class="tdesign-demo__panel-options-multiple"
          @change="onCheckedChange"
          @click="(e) => e.stopPropagation()"
        />
      </template>
      <template #suffixIcon>
        <chevron-down-icon />
      </template>
    </t-select-input>
    <t-tree :data="secondFilterTreeOptions" :line="true" expandAll activable hover transition @click="onTreeSelect">
      <template #label="{ node }">
        <span class="tree-node">
          <t-popup :content="node.label">
            <error-circle-icon
              v-if="
                riskObject[node.value] &&
                riskObject[node.value].level !== RISK_STATUS.NO &&
                riskObject[node.value].level !== RISK_STATUS.TO_BE_CONFIRMED
              "
              class="icon"
              style="color: #e34d59"
            />
            <help-circle-icon
              v-if="riskObject[node.value] && riskObject[node.value].level === RISK_STATUS.TO_BE_CONFIRMED"
              class="icon"
              style="color: #f29a5f"
            />
            <close-circle-icon
              v-if="
                questionObject[node.value] && questionObject[node.value].isError && answer[node.value] === undefined
              "
              class="icon"
              style="color: #e34d59"
            />
            {{ node.label }}
          </t-popup>
        </span>
      </template>
    </t-tree>
  </div>
</template>

<script>
import { ChevronDownIcon, ErrorCircleIcon, HelpCircleIcon, CloseCircleIcon } from 'tdesign-icons-vue';
import { checkboxOptions, TREE_FILTER_ACTIONS, QUESTIONNAIRE_STATUS } from '@/constants/risk-assessment-management';
import { RISK_STATUS, riskCheckboxOptions } from '@/constants/risk-assessment-template';

export default {
  components: { ChevronDownIcon, ErrorCircleIcon, HelpCircleIcon, CloseCircleIcon },
  props: {
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    status: {
      type: Number,
      default: QUESTIONNAIRE_STATUS.TO_BE_FILLED,
    },
    treeOptions: {
      type: Array,
      default() {
        return [];
      },
    },
    answer: {
      type: Object,
      default() {
        return {};
      },
    },
    questionObject: {
      type: Object,
      default() {
        return {};
      },
    },
    riskObject: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      RISK_STATUS,
      selectValue: [],
    };
  },
  computed: {
    currentCheckboxOptions() {
      if (this.status === QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
        return checkboxOptions;
      }
      return riskCheckboxOptions;
    },
    checkboxValue() {
      return this.selectValue.map((i) => i.value);
    },
    checkedOptions() {
      const obj = {};
      this.selectValue.forEach((item) => {
        obj[item.value] = true;
      });
      return obj;
    },
    filterTreeOptions() {
      let newTree = JSON.parse(JSON.stringify(this.treeOptions));

      if (this.selectValue.length > 0) {
        if (this.status === QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
          newTree = newTree.filter((p_node) => {
            p_node.children = p_node.children.filter((node) => {
              if (this.checkedOptions[TREE_FILTER_ACTIONS.REQUIRED] && !this.questionObject[node.value].isRequired) {
                return false;
              }
              if (this.checkedOptions[TREE_FILTER_ACTIONS.UNFILLED] && this.answer[node.value] !== undefined) {
                return false;
              }
              if (this.checkedOptions[TREE_FILTER_ACTIONS.FLAG] && !this.questionObject[node.value].isFlag) {
                return false;
              }
              if (this.checkedOptions[TREE_FILTER_ACTIONS.ASSIGNED] && !this.questionObject[node.value].readOnly) {
                return false;
              }
              if (this.checkedOptions[TREE_FILTER_ACTIONS.MESSAGE] && !this.questionObject[node.value].messageNum) {
                return false;
              }
              return true;
            });
            return p_node.children.length > 0;
          });
        } else {
          newTree = newTree.filter((p_node) => {
            p_node.children = p_node.children.filter((node) => {
              const riskLevel = this.riskObject[node.value] ? this.riskObject[node.value].level : RISK_STATUS.NO;
              if (!this.checkedOptions[riskLevel]) {
                return false;
              }
              return true;
            });
            return p_node.children.length > 0;
          });
        }
      }

      const activeNodeName = [];
      newTree.forEach((p_node) => {
        activeNodeName.push(p_node.value);
        p_node.children.forEach((node) => {
          activeNodeName.push(node.value);
        });
      });
      this.$emit('input', activeNodeName);

      return newTree;
    },
    // 二次过滤树节点选项，不展示隐藏问题的节点
    secondFilterTreeOptions() {
      const newTree = JSON.parse(JSON.stringify(this.filterTreeOptions));
      return newTree.filter((p_node) => {
        p_node.children = p_node.children.filter((node) => {
          if (this.questionObject[node.value].unVisible) {
            return false;
          }
          return true;
        });
        return p_node.children.length > 0;
      });
    },
  },
  // watch: {
  // 为了让tree响应式的处理
  // answer: {
  //   handler() {
  //     this.selectValue = [...this.selectValue];
  //   },
  // },
  // questionObject: {
  //   handler() {
  //     this.selectValue = [...this.selectValue];
  //   },
  //   deep: true,
  // },
  // },
  methods: {
    onTreeSelect(e) {
      this.$emit('onTreeSelect', e);
    },
    onTagChange(value, { item }) {
      this.selectValue = this.selectValue.filter((i) => i.label !== item);
    },
    onCheckedChange(value, { type, current }) {
      if (type === 'check') {
        const option = this.currentCheckboxOptions.find((i) => i.value === current);
        this.selectValue.push(option);
      } else {
        this.selectValue = this.selectValue.filter((i) => i.value !== current);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.answer-tree {
  height: calc(100vh - 265px);
  overflow-y: auto;
  margin-right: 24px;
  /deep/ .t-popup {
    position: relative;
    right: 24px;
  }
  .icon {
    position: relative;
    top: -1.7px;
  }
}
</style>
